package com.mall.order.services;

import com.mall.order.OrderService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.converter.OrderDetailConverter;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    //用tkMyBatis实现单表查询
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    StockMapper stockMapper;
    @Autowired
    OrderDetailConverter orderConverter;//注入类型转换器

    @Override
    public OrderDetailByIdResponse getOrderDetailById(OrderDetailRequest request) {
        OrderDetailByIdResponse cancelOrderResponse = new OrderDetailByIdResponse();
        OrderDetailById orderDetailById = new OrderDetailById();
        try {//正常处理，没有异常
            request.requestCheck(); //参数校验
            //根据订单id查询里面的user_id，再查询tb_member表对应用户名，查询订单状态
            //select o.payment as orderTotal, userName ,m.id as userId from tb_order as o,tb_member as m where o.user_id=m.id and o.order_id="xx";
            orderDetailById = orderMapper.selectUserByOrderId(request.getOrderId());

            //根据订单id查询tb_order_item表里的多条订单商品详情
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(request.getOrderId());
            //OrderItem比实际业务要求多了个status变量，用convertor进行转换
            List<OrderItemDto> orderItemDtos = orderConverter.orderItemsToOrderItemDto(orderItems);
            orderDetailById.setGoodsList(orderItemDtos);

            //根据订单id查询tb_order_shipping表里的收货信息
            //select receiver_phone as tel,receiver_address as streetName from tb_order_shipping where order_id="xx";
            //不能用原来的对象接收收货地址，因为对象里的其它变量值会变成null
            //错：cancelOrderResponse = orderMapper.selectAddressByOrderId((request.getOrderId()));
            OrderDetailById temp = orderMapper.selectAddressByOrderId((request.getOrderId()));
            orderDetailById.setStreetName(temp.getStreetName());
            orderDetailById.setTel(temp.getTel());

            //数据查询成功，封装状态码
            cancelOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
            cancelOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
            //封装订单详情对象
            cancelOrderResponse.setOrderDetailById(orderDetailById);
        } catch (Exception e) {//中间有异常，返回错误码
            cancelOrderResponse.setCode(OrderRetCode.SYSTEM_ERROR.getCode());
            cancelOrderResponse.setMsg(OrderRetCode.SYSTEM_ERROR.getMessage());
        }
        return cancelOrderResponse;
    }

    //根据订单id取消订单
    // （修改订单状态为7、更新时间，修改tb_order_item表单库存锁定，
    // tb_stock表修改库存锁定、释放库存）
    @Override
    public CancelOrderResponse cancelOrderById(CancelOrderRequest request) {
        CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();
        try {//正常处理，没有异常
            request.requestCheck(); //参数校验
            //根据订单id修改订单状态
            Order order = new Order();
            order.setOrderId(request.getOrderId());
            order.setStatus(7);
            Date currentTime = new Date();
            order.setUpdateTime(currentTime);
            order.setCloseTime(currentTime);
            orderMapper.updateByPrimaryKeySelective(order);
            modifyStock(request.getOrderId());//修改库存状态

            //数据更新成功，封装状态码
            cancelOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
            cancelOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {//中间有异常，返回错误码
            cancelOrderResponse.setCode(OrderRetCode.SYSTEM_ERROR.getCode());
            cancelOrderResponse.setMsg(OrderRetCode.SYSTEM_ERROR.getMessage());
        }
        return cancelOrderResponse;
    }


    //修改锁定库存
    private void modifyStock(String orderId) {
        //根据订单id修改tb_order_item表里的多条订单状态
        orderItemMapper.updateStockStatus(2, orderId);

        //修改tb_stock表
        //获得订单详情
        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
        for (OrderItem orderItem : orderItems) {
            //根据商品id获得所有要修改的商品规格
            Example example = new Example(Stock.class);
            example.createCriteria().andEqualTo("itemId", orderItem.getItemId());
            List<Stock> stocks = stockMapper.selectByExample(example);
            for (Stock stock : stocks) {
                //库存锁定数量 - 取消订单的商品数量=新锁定数量
                stock.setLockCount(stock.getLockCount() - orderItem.getNum());
                stock.setStockCount(stock.getStockCount() + orderItem.getNum());
                Example example1 = new Example(Stock.class);
                example1.createCriteria().andEqualTo("itemId", stock.getItemId());
                stockMapper.updateByExample(stock, example1);
            }
        }
    }


    //根据id删除订单
    @Override
    public DeleteOrderResponse deleteOrderById(DeleteOrderRequest request) {
        DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();
        try {//正常处理，没有异常
            request.requestCheck(); //参数校验

            //查找要删除的订单
            Order deletedOrder = orderMapper.selectByPrimaryKey(request.getOrderId());
            //只有要删除的订单状态为0，才要修改库存
            if (deletedOrder.getStatus() == 0) {
                modifyStock(request.getOrderId());//修改锁定库存
            }

            //根据订单id修改订单状态
            Order order = new Order();
            order.setOrderId(request.getOrderId());
            order.setStatus(5);
            Date currentTime = new Date();
            order.setUpdateTime(currentTime);
            order.setCloseTime(currentTime);
            orderMapper.updateByPrimaryKeySelective(order);


            //数据更新成功，封装状态码
            deleteOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
            deleteOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {//中间有异常，返回错误码
            deleteOrderResponse.setCode(OrderRetCode.SYSTEM_ERROR.getCode());
            deleteOrderResponse.setMsg(OrderRetCode.SYSTEM_ERROR.getMessage());
        }
        return deleteOrderResponse;
    }
}

